package com.studentstreet;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.studentstreet.adapter.GoodsItemAdapter;
import com.studentstreet.component.AbstractCommonActivity;
import com.studentstreet.component.LoadStateView;
import com.studentstreet.entities.GoodsEntity;
import com.studentstreet.tools.HttpHelper;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.Util;
import com.studentstreet.tools.dbhelper.GoodsDBHelper;

/**
 * @author likebamboo
 * 
 */
public class SearchResultActivity extends AbstractCommonActivity {
	// Title标题
	private TextView titleText;
	// Login Button登录按钮
	private Button login_bt;
	// 头部左边的按钮
	private ImageButton backImgBt = null;

	// loadView
	private LoadStateView loadView = null;

	// 搜索描述
	private String search_info = "";

	// 搜索类别
	private String classKey = "";
	// 搜索价格范围
	private String priceKey = "";
	// 搜索关键字
	private String key = "";

	// 搜索结果Json字符串
	private String resultJson = "";

	// ListView
	private ListView goodsListView = null;
	// 适配器
	private GoodsItemAdapter adapter = null;
	// 搜索结果List
	private List<GoodsEntity> goodsList = null;

	// 标识有符合条件的结果
	private final static int RESULT_LIST = 0x10001;
	// 标识没有符合条件的结果
	private final static int RESULT_EMPTY = 0x10002;
	// 标识网络出现错误
	private final static int ERROR = 0x10003;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_result);
		// 将当前Activity压入堆栈中
		MyApp.getInstance().addActivity(this);
		// 获得从上个Activity传来的数据
		Intent intent = getIntent();
		classKey = intent.getStringExtra("class");
		priceKey = intent.getStringExtra("price");
		key = intent.getStringExtra("key");
		search_info = intent.getStringExtra("search_info");

		// 初始化头部
		initHeader();
		// 初始化LoadView
		loadView = (LoadStateView) findViewById(R.id.downloadStatusBox);
		// 初始化ListView
		goodsListView = (ListView) findViewById(R.id.goodsList);
		// ListView的头部，
		TextView textView = new TextView(this);
		textView.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.shape_bg));
		textView.setGravity(Gravity.CENTER);
		textView.setText(Html.fromHtml(search_info));
		// 为List添加头部信息
		// OEM fix issue1 @20121231
		goodsListView.addHeaderView(textView, null, false);
		// 创建适配器
		adapter = new GoodsItemAdapter(this, goodsListView);
		adapter.setKey(key);
		// 为ListView添加适配器
		goodsListView.setAdapter(adapter);

		// 为ListView添加ItemClick
		goodsListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View view,
							int position, long arg3) {
						Bundle data = new Bundle();
						// 之所以position-1是因为添加了头部之后，位置会偏移，头部为position0
						data.putParcelable("goods", goodsList.get(position - 1));
						// 跳转到商品详情界面
						Intent intent = new Intent(SearchResultActivity.this,
								GoodsDetailActivity.class);
						intent.putExtra("goods_detail", data);
						startActivity(intent);
					}
				});

		// 初始化搜索结果列表
		goodsList = new ArrayList<GoodsEntity>();
		// 搜索结果
		searchResult();
		// 设置 "重新加载" 监听器
		loadView.setOnReloadClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				searchResult();
			}
		});
	}

	// 初始化头部
	private void initHeader() {
		// 返回按钮
		backImgBt = (ImageButton) findViewById(R.id.header_imgBt);
		// 头部中间的标题
		titleText = (TextView) findViewById(R.id.title);
		// 登录按钮
		login_bt = (Button) findViewById(R.id.login_bt);
		// 返回按钮
		backImgBt.setImageResource(R.drawable.back);
		backImgBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		// 头部中间的标题
		titleText.setText(getResources().getString(R.string.search_result));
		// 登录按钮
		login_bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 显示登录对话框
				Intent intent = new Intent(SearchResultActivity.this,
						LoginDialog.class);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		PreferenceTools prefTools = new PreferenceTools(this);
		// 判断是否已经登录
		if (!prefTools.isLogin()) {
			return;
		}
		// 登录后修改登录按钮上的text
		String userName = prefTools.getUserName();
		if (!userName.equals("")) {
			login_bt.setText(userName);
			// 去掉登录按钮文本右边的图标
			login_bt.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
					null);
		}
	}

	// 获得搜索结果
	private void searchResult() {
		loadView.startLoad();
		new Thread(new Runnable() {
			@Override
			public void run() {
				// 使用apache HTTP客户端实现
				String urlStr = Util.BASE_URL + "/servlet/SearchServlet";
				// 创建网络连接工具对象
				HttpHelper helper = new HttpHelper(urlStr);
				// 添加参数
				// 搜索类别
				helper.addParam("classKey", classKey);
				// 价格范围
				helper.addParam("priceKey", priceKey);
				// 关键字
				helper.addParam("key", key);
				// 获得服务器返回的数据
				resultJson = helper.getResponse();
				// 如果返回的数据为""，表示网络错误
				if ("".equals(resultJson)) {
					// 网络出错，显示错误信息
					sendMessage(ERROR);
					return;
				}
				// 将数据添加到适配器中，如果成功，发送一个Message
				if (addData(resultJson)) {
					// 发送Message
					sendMessage(RESULT_LIST);
				}
			}
		}).start();
	}

	private boolean addData(String json) {
		if ("".equals(resultJson)) {
			// 未取得任何数据，显示错误信息
			sendMessage(ERROR);
			return false;
		}
		// 没有符合搜索条件的结果，显示提示信息
		if ("[]".equals(resultJson)) {
			sendMessage(RESULT_EMPTY);
			return false;
		}
		Type listType = new TypeToken<ArrayList<GoodsEntity>>() {
		}.getType();
		// 创建Gson 对象
		Gson gson = new Gson();
		// 将Json数据转化为List<GoodsEntity>
		goodsList = gson.fromJson(json, listType);
		// 把商品图片路径补充完整
		for (GoodsEntity goods : goodsList) {
			goods.setImageUrl(Util.BASE_GOODS_IMG_URL + goods.getImageUrl());
		}
		// 将数据保存到数据库
		GoodsDBHelper dbHelper = new GoodsDBHelper(this);
		dbHelper.saveToDB(goodsList);
		// 填充adapter
		adapter.addGoods(goodsList);
		return true;
	}

	@Override
	protected void handleOtherMessage(int flag) {
		super.handleOtherMessage(flag);
		switch (flag) {
		// 得到符合条件的结果
		case RESULT_LIST:
			loadView.stopLoad();
			adapter.notifyDataSetChanged();
			break;
		// 没有符合条件的结果
		case RESULT_EMPTY:
			loadView.stopLoad();
			loadView.showEmpty(getResources().getString(
					R.string.search_result_empty));
			break;
		// 网络出错
		case ERROR:
			loadView.stopLoad();
			loadView.showError();
			break;
		default:
			break;
		}
	}

}
